<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\UserTempFilesModel;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Storage;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    const DEFAULT_UPLOAD_DIR = 'uploads';

    // 本次请求上传的文件（用于回滚删除）
    static $tempUploadFiles = [];


    public static function getLoginUser(Request $request)
    {
        /** @var User $user */
        $user = $request->user();
        return $user;
    }


    public static function getArrayQuery(Request $request, string $key, array $default = null): array
    {
        $val = $request->input($key, []);
        if (is_string($val)) {
            $ids = json_decode($val, true);
            if (empty($ids) || !is_array($ids)) {
                $val = [$val];
            } else {
                $val = $ids;
            }
        } elseif (!is_array($val)) {
            $val = [$val];
        }
        $params = array_values(array_filter($val, function ($item) {
            if (is_string($item)) {
                $item = str_replace(' ', '', $item);
            }
            return is_numeric($item) || !empty($item);
        }));
        if (empty($params) && is_array($default)) {
            $params = $default;
        }
        return $params;
    }


    /**
     * 上传文件
     * @param UploadedFile $file
     * @param string|null $disk 驱动
     * @param string $path 路径文件夹
     * @return string 文件名
     */
    public static function uploadFile(UploadedFile $file, string $disk = null, string $path = self::DEFAULT_UPLOAD_DIR)
    {
        if (is_null($disk)) {
            $disk = config('filesystems.default');
        }
        $disk = Storage::disk($disk);

        //将图片上传到OSS中，并返回图片路径信息 值如:avatar/WsH9mBklpAQUBQB4mL.jpeg
        $path = $disk->put($path, $file);

        //由于图片不在本地，所以我们应该获取图片的完整路径，
        //值如：https://test.oss-cn-hongkong.aliyuncs.com/avatar/8GdIcz1NaCZ.jpeg
        $url = $disk->url($path);
        array_push(self::$tempUploadFiles, $url);
        return $url;
    }

    /**
     * 文件系统中是否该路径的文件
     * @param string|null $path
     * @param string|null $disk
     * @return bool
     */
    public static function hasFile(string $path = null, string $disk = null)
    {
        if (empty($path)) {
            return false;
        }
        if (is_null($disk)) {
            $disk = config('filesystems.default');
        }
        return Storage::disk($disk)->has($path);
    }

    /**
     * 删除上传的文件
     * @param $fileName
     * @return bool|null
     */
    public static function destroyFile($fileName)
    {
        // http://jiyukeji.oss-cn-shenzhen.aliyuncs.com/uploads/W2qBk5ih9bCRYyvGugOAK5hrRMoX3b5tlZ6GiXZs.png
        if (is_string($fileName)) {
            $endPoint = config('filesystems.disks.oss.endpoint');
            $fileName = preg_replace("/.*{$endPoint}/", '', $fileName);
            return Storage::delete($fileName);
        } elseif (is_array($fileName)) {
            foreach ($fileName as $value) {
                self::destroyFile($value);
            }
        }

    }


}
